<script setup>
import {computed, onMounted, ref} from "vue";
import axios from "axios";
import {useRoute,useRouter} from "vue-router";
import {ArrowDown, ArrowDownBold} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {gotoUserInfo} from "@/api/toMusicInfo.js";
const props = defineProps(['info'])
const emit = defineEmits([]);

const route = useRoute()
const router = useRouter()
// 评论计数
const comment1List = ref([{
  id: 0,
  avatar: "",
  account: 0,
  username: "",
  commentTime: "",
  likeCount: 0,
  commentCount: 0,
  content: "",
  isLiked: false,
  // 是否显示对话框 只在前端有
  isReply: false,
  // 回复内容 只在前端有
  reply: "",
  // 是否显示展开回复 只在前端有
  isExpand: false,
  // 回复评论区 只在前端有
  replyList: [{
    id: 0,
    avatar: "",
    account: 0,
    username: "",
    commentTime: "",
    likeCount: 0,
    // 这一条其实是不需要的
    commentCount: 0,
    content: "",
    isLiked: false,
    // 是否显示对话框 只在前端有
    isReply: false,
    // 回复内容 只在前端有
    reply: ""
  }]
}]);
const textarea = ref("")
const textareaCount = computed(() => {
      return 300 - textarea.value.length
    }
)
onMounted( () => {


  // 请求歌曲 评论列表及其信息
  const musicCommentListUrl = "/music/comment/show?biz=0&bizId=" + route.params.id + "&account=" + localStorage.getItem('account')
  axios.get(musicCommentListUrl
  ).then((res)=>{
    if (res.data.flag) {
      comment1List.value = res.data.data
    } else {
      console.log(res.data.message)
    }
  })
  .catch(err => {
    console.log(err.data)
  })

});




// 完成评论方法
function comment(biz) {

  // 判断一下 如果为空不发送
  if (textarea.value.trim() === '') {
    ElMessage.error("评论不能为空")
    textarea.value = ''
    return
  }

  const formData = {
    account: localStorage.getItem('account'),
    bizId: route.params.id,
    biz: biz,
    content: textarea.value
  }

  // 发请求添加评论信息到数据库 请求成功后 清除提示成功信息并评论区信息，错误的话 提示错误
  const url = "/music/comment/add"
  axios.post(url, JSON.stringify(formData)).then((res)=>{
    if (res.data.flag) {
      // 重新刷新 请求接口
      ElMessage.success("发布评论成功！")
      textarea.value = ''
      if (biz === 0) {
        // 如果是歌曲 就要对评论总数进行自增 冒泡事件
        increaseCommentCount()
      }
      // 请求歌曲 评论列表及其信息
      const musicCommentListUrl = "/music/comment/show?biz=0&bizId=" + route.params.id + "&account=" + localStorage.getItem('account')
      axios.get(musicCommentListUrl
      ).then((res)=>{
        if (res.data.flag) {
          comment1List.value = res.data.data
        } else {
          console.log(res.data.message)
        }
      })
      .catch(err => {
        console.log(err.data)
      })


    } else {
      ElMessage.error(res.data.message)
      console.log(res.data.message)
    }
  }).catch(err => {
    console.log(err.data)
  })

}
// 冒泡方法 评论数自增
function increaseCommentCount() {
  emit('increaseCommentCount');
}

// 完成回复评论方法
function reply(item,biz,id) {

  // 判断一下 如果为空不发送
  if (item.reply === undefined || item.reply.trim() === '') {
    ElMessage.error("评论不能为空")
    item.reply = ''
    return
  }
  // 判断一下 如果item.id和id不相同 则证明是三级评论 以上 就在前面加上
  // <span style="color: red">@ + 这里面传回复的内个账号的用户名（从父标签中获取这个值）</span>
  // <span style="color: red">@ </span>

  let formData = {
    account: localStorage.getItem('account'),
    bizId: id,
    biz: biz,
    content: item.reply
  }
  if (item.id !== id) {
    formData = {
      account: localStorage.getItem('account'),
      bizId: id,
      biz: biz,
      content: item.reply + '\n' + '<span style="color: #ff8563">@' + item.username + '：</span>' + item.content
    }
  }

  // 发请求添加评论信息到数据库 请求成功后 清除提示成功信息并评论区信息，错误的话 提示错误
  const url = "/music/comment/add"
  axios.post(url, JSON.stringify(formData)).then((res)=>{
    if (res.data.flag) {
      // 重新刷新 请求接口
      ElMessage.success("发布评论成功！")
      item.reply = ''
      if (biz === 0) {
        // 如果是歌曲 就要对评论总数进行自增 冒泡事件
        increaseCommentCount()
      }
      // 请求歌曲 评论列表及其信息
      const musicCommentListUrl = "/music/comment/show?biz=0&bizId=" + route.params.id + "&account=" + localStorage.getItem('account')
      axios.get(musicCommentListUrl
      ).then((res)=>{
        if (res.data.flag) {
          comment1List.value = res.data.data
        } else {
          console.log(res.data.message)
        }
      })
      .catch(err => {
        console.log(err.data)
      })


    } else {
      ElMessage.error(res.data.message)
      console.log(res.data.message)
    }
  }).catch(err => {
    console.log(err.data)
  })
}



// 让代码耦合度低一点 使逻辑更加清楚一点 把接口给分开
function like(item) {
  // 给一条评论点赞 需要的参数
  const formData = {
    account: localStorage.getItem('account'),
    bizId: item.id,
    biz: 1
  }

  // 发请求添加评论信息到数据库 请求成功后 清除提示成功信息并评论区信息，错误的话 提示错误
  const url = "/music/like"
  axios.post(url, JSON.stringify(formData)).then((res)=>{
    if (res.data.flag) {
      // 重新刷新 请求接口
      ElMessage.success("点赞成功")
      item.isLiked = !item.isLiked;
      item.likeCount++
    } else {
      ElMessage.error("点赞失败")
      console.log(res.data.message)
    }
  }).catch(err => {
    console.log(err.data)
  })
}

function unlike(item) {
  // 给一条评论点赞 需要的参数
  const formData = {
    account: localStorage.getItem('account'),
    bizId: item.id,
    biz: 1
  }

  // 发请求添加评论信息到数据库 请求成功后 清除提示成功信息并评论区信息，错误的话 提示错误
  const url = "/music/like"
  axios.post(url, JSON.stringify(formData)).then((res)=>{
    if (res.data.flag) {
      ElMessage.success("点赞取消成功！")
      item.isLiked = !item.isLiked;
      item.likeCount--
    } else {
      ElMessage.error("点赞取消失败！")
      console.log(res.data.message)
    }
  }).catch(err => {
    console.log(err.data)
  })
}

// 显示回复对话框
function openReply(item) {
  item.isReply = true
}
// 关闭回复对话框
function closeReply(item) {
  item.isReply = false
}
function expandReply(item) {
  item.isExpand = !item.isExpand
  // 然后请求数据 给item.replyList赋值
  // 请求歌曲 评论列表及其信息 biz为1 给评论业务评论 bizId在item里取
  const musicCommentListUrl = "/music/comment/show?biz=1&bizId=" + item.id + "&account=" + localStorage.getItem('account')
  axios.get(musicCommentListUrl
  ).then((res)=>{
    if (res.data.flag) {
      item.replyList = res.data.data
    } else {
      console.log(res.data.message)
    }
  })
  .catch(err => {
    console.log(err.data)
  })
}


</script>

<template>


  <div class="comment-area">

    <h2 style="display: inline-block;font-weight: normal">评论</h2>
    <span style="display: inline-block;margin-left: 12px;font-size: 14px;color: #999999">共{{info.commentCount}}条评论</span>

    <div style="box-sizing: border-box;margin-top: 15px;overflow: hidden;height: 103.6px;width:857px;position: relative">
      <textarea placeholder="说说你的看法吧" v-model="textarea"></textarea>
      <div v-if="textareaCount >= 0" style="color: #999999;font-size: 14px;position: absolute;bottom: 5px;right: 10px">剩余<span style="font-weight: 200;color: #e96161">{{ textareaCount }}</span>字</div>
      <div v-else style="color: #999999;font-size: 14px;position: absolute;bottom: 5px;right: 10px">超过<span style="font-weight: 200;color: #e96161">{{ -textareaCount }}</span>字</div>
    </div>
    <button @click="comment(0)" class="sendComment-button">发表评论</button>

    <h3 style="margin-top: 60px;height: 60px;line-height: 60px;color: black;border-bottom: 1px solid #e3e3e3;font-size: 16px;font-weight: normal">全部评论({{info.commentCount}})</h3>


    <div v-for="(item,index) in comment1List" :key="index" style="border-bottom: 1px solid #e3e3e3;
        display: flex;gap: 15px;padding: 15px 0 30px 15px;width: 857px;box-sizing: border-box;
      ">
      <img @click="gotoUserInfo(router, item.account)" style="margin-top: 2px;width: 40px;height: 40px;border-radius: 50%" :src="item.avatar !== null ? item.avatar : '/src/assets/img/icon.png'">
      <div style="display: flex;width: 787px;word-wrap: break-word;flex-direction: column;color: #999;font-size: 14px">
        <!-- 一些头信息 时间 评论者名称等等 -->
        <div @click="gotoUserInfo(router, item.account)" class="hover" style="line-height: 26px;height: 26px">{{item.username}}</div>
        <div style="height: 20px;line-height: 20px">{{item.commentTime}}</div>
        <!-- 评论内容 -->
        <div style="margin-bottom: 4px;white-space: pre-wrap;margin-top: 13px;color: black;line-height: 26px">{{item.content}}</div>


        <!-- 这俩就是点赞信息 -->
        <div style="display: flex;align-items: center;gap: 20px">

          <div @click="unlike(item)" style="display: flex;font-weight: 1;align-items: center;color: #e96161" v-if="item.isLiked">
            <i class="comment-liked-icon"></i>
            <div v-if="item.likeCount > 0">{{ item.likeCount }}</div>
          </div>
          <div @click="like(item)" style="display: flex;font-weight: 1;align-items: center;color: black" v-else>
            <i class="comment-like-icon"></i>
            <div v-if="item.likeCount > 0">{{ item.likeCount }}</div>
          </div>
          <!-- 回复评论方法 把需要所回复的评论id传过去 -->
          <div class="hover" @click="openReply(item)">回复</div>

        </div>

        <div v-if="item.isReply">
          <div style="margin-top: 15px;overflow: hidden;height: 103.6px;width:800px;position: relative">
            <textarea placeholder="说说你的看法吧" v-model="item.reply" style="width: 787px!important;min-height: 100px;box-sizing: border-box"></textarea>

            <div v-if="item.reply == null" style="color: #999999;font-size: 14px;position: absolute;bottom: 7px;right: 20px">剩余<span style="font-weight: 200;color: #e96161">300</span>字</div>
            <div v-else-if="item.reply.length <= 300" style="color: #999999;font-size: 14px;position: absolute;bottom: 7px;right: 20px">剩余<span style="font-weight: 200;color: #e96161">{{ 300 - item.reply.length }}</span>字</div>
            <div v-else style="color: #999999;font-size: 14px;position: absolute;bottom: 7px;right: 20px">超过<span style="font-weight: 200;color: #e96161">{{ item.reply.length-300 }}</span>字</div>
          </div>
          <div>
            <button style="margin-left: auto" @click="closeReply(item)" class="cancelComment-button">取消</button>
            <button style="margin-left: auto;margin-right: 6px" @click="reply(item,1, item.id)" class="sendComment-button">回复</button>
          </div>
        </div>

        <!-- 然后是展开回复 如果有则可以展开 -->
        <div @click="expandReply(item)" v-if="item.commentCount > 0 " class="hover" style="margin-top: 2px;display: flex;align-items: flex-end;gap: 5px">
          查看{{item.commentCount}}条回复
          <el-icon v-if="item.isExpand" style="font-size: 16px"><ArrowUp  /></el-icon>
          <el-icon v-else style="font-size: 16px"><ArrowDown  /></el-icon>
        </div>


        <div v-if="item.isExpand" class="replyArea">


          <div v-for="(item1,index) in item.replyList" :key="index" style="border-bottom: 1px solid #e3e3e3;
        display: flex;gap: 15px;padding: 15px 0 30px;width: 857px;box-sizing: border-box;
      ">
            <img @click="gotoUserInfo(router, item.account)" style="margin-top: 2px;width: 40px;height: 40px;border-radius: 50%" :src="item1.avatar !== null ? item1.avatar : '/src/assets/img/icon.png'">
            <div style="display: flex;width: 692px;word-wrap: break-word;flex-direction: column;color: #999;font-size: 14px">
              <!-- 一些头信息 时间 评论者名称等等 -->
              <div @click="gotoUserInfo(router, item.account)" class="hover" style="line-height: 26px;height: 26px">{{item1.username}}</div>
              <div style="height: 20px;line-height: 20px">{{item1.commentTime}}</div>
              <!-- 评论内容 -->
              <div style="margin-bottom: 4px;white-space: pre-wrap;margin-top: 13px;color: black;line-height: 26px" v-html="item1.content"></div>


              <!-- 这俩就是点赞信息 -->
              <div style="display: flex;align-items: center;gap: 20px">

                <div @click="unlike(item1)" style="display: flex;font-weight: 1;align-items: center;color: #e96161" v-if="item1.isLiked">
                  <i class="comment-liked-icon"></i>
                  <div v-if="item1.likeCount > 0">{{ item1.likeCount }}</div>
                </div>
                <div @click="like(item1)" style="display: flex;font-weight: 1;align-items: center;color: black" v-else>
                  <i class="comment-like-icon"></i>
                  <div v-if="item1.likeCount > 0">{{ item1.likeCount }}</div>
                </div>
                <!-- 回复评论方法 把需要所回复的评论id传过去 -->
                <div class="hover" @click="openReply(item1)">回复</div>

              </div>

              <div v-if="item1.isReply">
                <div style="margin-top: 15px;overflow: hidden;height: 103.6px;width:692px;position: relative">
                  <textarea placeholder="说说你的看法吧" v-model="item1.reply" style="width: 692px!important;min-height: 100px;box-sizing: border-box"></textarea>
                  <div v-if="item1.reply == null" style="color: #999999;font-size: 14px;position: absolute;bottom: 8px;right: 15px">剩余<span style="font-weight: 200;color: #e96161">300</span>字</div>
                  <div v-else-if="item1.reply.length <= 300" style="color: #999999;font-size: 14px;position: absolute;bottom: 8px;right: 15px">剩余<span style="font-weight: 200;color: #e96161">{{ 300 - item1.reply.length }}</span>字</div>
                  <div v-else style="color: #999999;font-size: 14px;position: absolute;bottom: 8px;right: 15px">超过<span style="font-weight: 200;color: #e96161">{{ item1.reply.length - 300 }}</span>字</div>
                </div>
                <div>
                  <button style="margin-left: auto" @click="closeReply(item1)" class="cancelComment-button">取消</button>
                  <button style="margin-left: auto;margin-right: 6px" @click="reply(item1,1, item.id)" class="sendComment-button">回复</button>
                </div>
              </div>



            </div>
          </div>



        </div>

      </div>
    </div>


  </div>
</template>

<style scoped>
.replyArea {
  width: 787px;
  box-sizing: border-box;
  margin-top: 10px;
  padding: 10px 20px;
  background-color: rgba(0, 0, 0, 0.05);
}
.hover:hover {
  cursor: pointer;
  color: #ff8763;
}
.sendComment-button {
  color: white;
  background-color: #ff8563;
  border: 0;
  float: right;
  text-align: center;
  width: 81px;
  line-height: 28px;
  height: 28px;
  margin-top: 12px;
  border-radius: 2px;
  font-size: 14px;
  cursor: pointer;
}
.cancelComment-button {
  background-color: white;
  border: 1px solid #d5d5d5;
  float: right;
  text-align: center;
  width: 81px;
  line-height: 27px;
  height: 28px;
  margin-top: 12px;
  border-radius: 2px;
  font-size: 14px;
  cursor: pointer;

}
textarea {
  resize: none;
  outline: none;
  min-height: 66px;
  width: 827.4px;
  display: block;
  padding: 18.8px 14.8px;
  color: #333;
  font-size: 14px;
  font-family: poppin, Tahoma, Arial, 微软雅黑, sans-serif;
  white-space: pre-wrap;
  border: 1px solid #ececec;
  background-color: #f5f5f5;
}
.comment-area {
  margin-top: 70px;
  width: 857px;
  font-family: poppin, Tahoma, Arial, \5FAE\8F6F\96C5\9ED1, sans-serif!important;
}

i:not(.el-icon){
  width: 34px;
  height: 34px;
  display: inline-block;
  background: url("/src/assets/img/total2.png") no-repeat;
  margin-left: -6px;
  margin-right: -2px;
}

.comment-liked-icon {
  background-position: 0 -50px!important;
  scale: 0.5;
  cursor:pointer;
}
.comment-like-icon {
  background-position: -50px -50px!important;
  scale: 0.5;
  cursor:pointer;
}
img {
  cursor: pointer;
}
</style>
